<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=7.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.ico?v=7.0.0">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '7.0.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="注：本文出自博主 Chloneda：个人博客 | 博客园 | Github | Gitee | 知乎 前言今天我们来聊聊Elasticsearch客户端的类型。我们知道Elasticsearch是一种分布式的海量数据搜索与分析的技术，可以用于电商网站、门户网站、企业IT系统等各种场景下的搜索引擎，也可以用于对海量的数据进行近实时的数据分析。 但Elasticsearch版本迭代更新太快，这就意味着">
<meta name="keywords" content="Elasticsearch">
<meta property="og:type" content="article">
<meta property="og:title" content="Elasticsearch客户端源码剖析">
<meta property="og:url" content="https://chloneda.github.io/blog/es-clients/index.html">
<meta property="og:site_name" content="Chloneda">
<meta property="og:description" content="注：本文出自博主 Chloneda：个人博客 | 博客园 | Github | Gitee | 知乎 前言今天我们来聊聊Elasticsearch客户端的类型。我们知道Elasticsearch是一种分布式的海量数据搜索与分析的技术，可以用于电商网站、门户网站、企业IT系统等各种场景下的搜索引擎，也可以用于对海量的数据进行近实时的数据分析。 但Elasticsearch版本迭代更新太快，这就意味着">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-02-25T15:24:34.498Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Elasticsearch客户端源码剖析">
<meta name="twitter:description" content="注：本文出自博主 Chloneda：个人博客 | 博客园 | Github | Gitee | 知乎 前言今天我们来聊聊Elasticsearch客户端的类型。我们知道Elasticsearch是一种分布式的海量数据搜索与分析的技术，可以用于电商网站、门户网站、企业IT系统等各种场景下的搜索引擎，也可以用于对海量的数据进行近实时的数据分析。 但Elasticsearch版本迭代更新太快，这就意味着">



  <link rel="alternate" href="/rss2.html" title="Chloneda" type="application/atom+xml">




  <link rel="canonical" href="https://chloneda.github.io/blog/es-clients/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Elasticsearch客户端源码剖析 | Chloneda</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chloneda</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">简约的程序员</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-project">

    
    
    
      
    

    

    <a href="/project/" rel="section"><i class="menu-item-icon fa fa-fw fa-github"></i> <br>项目</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-links">

    
    
    
      
    

    

    <a href="/links/" rel="section"><i class="menu-item-icon fa fa-fw fa-link"></i> <br>友链</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chloneda.github.io/blog/es-clients/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chloneda">
      <meta itemprop="description" content="Less is more">
      <meta itemprop="image" content="/images/chloneda.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chloneda">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Elasticsearch客户端源码剖析

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2020-02-25 23:24:34" itemprop="dateCreated datePublished" datetime="2020-02-25T23:24:34+08:00">2020-02-25</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Elasticsearch/" itemprop="url" rel="index"><span itemprop="name">Elasticsearch</span></a></span>

                
                
              
            </span>
          

          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon">
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>注：本文出自博主 Chloneda</strong>：<a href="https://chloneda.github.io/">个人博客</a> | <a href="https://www.cnblogs.com/chloneda" target="_blank" rel="noopener">博客园</a> | <a href="https://github.com/chloneda" target="_blank" rel="noopener">Github</a> | <a href="https://gitee.com/chloneda" target="_blank" rel="noopener">Gitee</a> | <a href="https://www.zhihu.com/people/chl_vip/" target="_blank" rel="noopener">知乎</a></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>今天我们来聊聊Elasticsearch客户端的类型。我们知道Elasticsearch是一种分布式的海量数据搜索与分析的技术，可以用于电商网站、门户网站、企业IT系统等各种场景下的搜索引擎，也可以用于对海量的数据进行近实时的数据分析。</p>
<p>但Elasticsearch版本迭代更新太快，这就意味着在Elasticsearch升级过程中容易出现兼容性问题。也引出了今天对Elasticsearch客户端种类及使用的问题讨论！</p>
<h1 id="ES客户端种类"><a href="#ES客户端种类" class="headerlink" title="ES客户端种类"></a>ES客户端种类</h1><p>ES官方客户端有TransportClient、Java Low Level REST Client和Java High Level REST Client三种。官方文档对他们的说明是：</p>
<p><strong>TransportClient</strong></p>
<blockquote>
<p>We plan on deprecating the TransportClient in Elasticsearch 7.0 and removing it completely in 8.0.</p>
</blockquote>
<p><strong>Java Low Level REST Client</strong></p>
<blockquote>
<p>the official low-level client for Elasticsearch. It allows to communicate with an Elasticsearch cluster through http. Leaves requests marshalling and responses un-marshalling to users. It is compatible with all Elasticsearch versions.</p>
</blockquote>
<p><strong>Java High Level REST Client</strong></p>
<blockquote>
<p>the official high-level client for Elasticsearch. Based on the low-level client, it exposes API specific methods and takes care of requests marshalling and responses un-marshalling.</p>
</blockquote>
<p>意思就是说，TransportClient将会在将来版本进行废弃移除，官方建议使用Java High Level REST Client。</p>
<p>为什么会这样呢？这里涉及到两个问题：</p>
<ul>
<li>未来版本为什么会淘汰TransportClient客户端？</li>
<li>Java Low/High Level REST Client客户端优点在哪里？</li>
</ul>
<p>先别急，我们来看看这两个问题！</p>
<h1 id="客户端的使用"><a href="#客户端的使用" class="headerlink" title="客户端的使用"></a>客户端的使用</h1><p>各客户端使用需要引入相关依赖，这里统一引入相关依赖，后面就不多赘述了！</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- elasticsearch core --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;elasticsearch&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;<span class="variable">$&#123;elasticsearch.version&#125;</span>&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;!-- low level rest client --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;elasticsearch-rest-client&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;<span class="variable">$&#123;elasticsearch.version&#125;</span>&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;!-- high level rest client --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;elasticsearch-rest-high-level-client&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;<span class="variable">$&#123;elasticsearch.version&#125;</span>&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p><strong>注</strong>：TransportClient将会在8.x版本后完全移除！</p>
<h2 id="TransportClient"><a href="#TransportClient" class="headerlink" title="TransportClient"></a>TransportClient</h2><p>初始化TransportClient客户端代码示例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public TransportClient initTransportClient(String esClusterName,String host,String port) throws UnknownHostException &#123;</span><br><span class="line">    Settings settings = Settings.builder()</span><br><span class="line">            .put(<span class="string">"cluster.name"</span>, esClusterName)</span><br><span class="line">            .put(<span class="string">"client.transport.sniff"</span>, <span class="literal">true</span>)</span><br><span class="line">            .build();</span><br><span class="line">    TransportClient client = new PreBuiltTransportClient(settings)</span><br><span class="line">            .addTransportAddress(new TransportAddress(InetAddress.getByName(host),port);</span><br><span class="line"></span><br><span class="line">    <span class="built_in">return</span> client;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Java-Low-Level-REST-Client"><a href="#Java-Low-Level-REST-Client" class="headerlink" title="Java Low Level REST Client"></a>Java Low Level REST Client</h2><p>初始化 RestClient 客户端代码示例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public RestClient initRestClient(String host, int port) &#123;</span><br><span class="line">    RestClientBuilder builder = RestClient.builder(new HttpHost(host,</span><br><span class="line">            port, <span class="string">"http"</span>));</span><br><span class="line">    Header[] defaultHeaders = new Header[]&#123;new BasicHeader(<span class="string">"header"</span>, <span class="string">"value"</span>)&#125;;</span><br><span class="line">    builder.setDefaultHeaders(defaultHeaders);</span><br><span class="line">    RestClient restClient = builder.build();</span><br><span class="line">    <span class="built_in">return</span> restClient;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Java-High-Level-REST-Client"><a href="#Java-High-Level-REST-Client" class="headerlink" title="Java High Level REST Client"></a>Java High Level REST Client</h2><p>初始化 RestHighLevelClient 客户端代码示例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public RestHighLevelClient restHighLevelClient(List&lt;String&gt; hostArray) &#123;</span><br><span class="line">    //创建HttpHost数组，其中存放es主机和端口的配置信息</span><br><span class="line">    HttpHost[] httpHostArray = new HttpHost[hostArray.size()];</span><br><span class="line">    <span class="keyword">for</span> (int i = 0; i &lt; hostArray.size(); i++) &#123;</span><br><span class="line">        String item = hostArray.get(i);</span><br><span class="line">        httpHostArray[i] = new HttpHost(item.split(<span class="string">":"</span>)[0], </span><br><span class="line">                Integer.parseInt(item.split(<span class="string">":"</span>)[1]), </span><br><span class="line">                <span class="string">"http"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    //创建RestHighLevelClient客户端</span><br><span class="line">    <span class="built_in">return</span> new RestHighLevelClient(RestClient.builder(httpHostArray));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上就是初始化三种不同客户端的示例代码！下面我们深入客户端代码底层，看看他们之间有什么不一样？</p>
<h1 id="深入客户端的底层"><a href="#深入客户端的底层" class="headerlink" title="深入客户端的底层"></a>深入客户端的底层</h1><h2 id="TransportClient-1"><a href="#TransportClient-1" class="headerlink" title="TransportClient"></a>TransportClient</h2><p>TransportClient客户端自从Elasticsearch诞生以来，一直是Elasticsearch的一部分。 它是一个特殊的客户端，因为它使用传输层协议（TCP）与Elasticsearch进行通信，如果该客户端与其所使用的Elasticsearch不在同一版本上，则会导致兼容性问题。基于这个原因，官方会在8.x后完全移除！</p>
<p>因此，在这里就不对 TransportClient 客户端底层进行深究了！</p>
<h2 id="Java-Low-Level-REST-Client-1"><a href="#Java-Low-Level-REST-Client-1" class="headerlink" title="Java Low Level REST Client"></a>Java Low Level REST Client</h2><p>2016年，Elasticsearch官方发布了一个低级REST客户端，该客户端基于众所周知的Apache HTTP客户端，它允许使用 HTTP 与任何版本的Elasticsearch集群进行通信。 </p>
<p>我们来看看RestClient客户端的代码：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br></pre></td><td class="code"><pre><span class="line">package org.elasticsearch.client;</span><br><span class="line"></span><br><span class="line">public class RestClient implements Closeable &#123;</span><br><span class="line"></span><br><span class="line">    //已省略其他非必要属性代码。。。</span><br><span class="line">    </span><br><span class="line">    // RestClient 类构造器的第一个参数是 CloseableHttpAsyncClient，是Apache HTTP client 中的类，相关请求也是通过该参数</span><br><span class="line"></span><br><span class="line">    RestClient(CloseableHttpAsyncClient client, long maxRetryTimeoutMillis, Header[] defaultHeaders, HttpHost[] hosts, String pathPrefix, RestClient.FailureListener failureListener) &#123;</span><br><span class="line">        this.client = client;</span><br><span class="line">        this.maxRetryTimeoutMillis = maxRetryTimeoutMillis;</span><br><span class="line">        this.defaultHeaders = Collections.unmodifiableList(Arrays.asList(defaultHeaders));</span><br><span class="line">        this.failureListener = failureListener;</span><br><span class="line">        this.pathPrefix = pathPrefix;</span><br><span class="line">        this.setHosts(hosts);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    //已省略其他非必要代码。。。</span><br><span class="line"></span><br><span class="line">    public void performRequestAsync(String method, String endpoint, Map&lt;String, String&gt; params, HttpEntity entity, HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory, ResponseListener responseListener, Header... headers) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            Objects.requireNonNull(params, <span class="string">"params must not be null"</span>);</span><br><span class="line">            Map&lt;String, String&gt; requestParams = new HashMap(params);</span><br><span class="line">            String ignoreString = (String)requestParams.remove(<span class="string">"ignore"</span>);</span><br><span class="line">            Object ignoreErrorCodes;</span><br><span class="line">            <span class="keyword">if</span> (ignoreString == null) &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="string">"HEAD"</span>.equals(method)) &#123;</span><br><span class="line">                    ignoreErrorCodes = Collections.singleton(404);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    ignoreErrorCodes = Collections.emptySet();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                String[] ignoresArray = ignoreString.split(<span class="string">","</span>);</span><br><span class="line">                ignoreErrorCodes = new HashSet();</span><br><span class="line">                <span class="keyword">if</span> (<span class="string">"HEAD"</span>.equals(method)) &#123;</span><br><span class="line">                    ((Set)ignoreErrorCodes).add(404);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                String[] var12 = ignoresArray;</span><br><span class="line">                int var13 = ignoresArray.length;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">for</span>(int var14 = 0; var14 &lt; var13; ++var14) &#123;</span><br><span class="line">                    String ignoreCode = var12[var14];</span><br><span class="line"></span><br><span class="line">                    try &#123;</span><br><span class="line">                        ((Set)ignoreErrorCodes).add(Integer.valueOf(ignoreCode));</span><br><span class="line">                    &#125; catch (NumberFormatException var17) &#123;</span><br><span class="line">                        throw new IllegalArgumentException(<span class="string">"ignore value should be a number, found ["</span> + ignoreString + <span class="string">"] instead"</span>, var17);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            URI uri = buildUri(this.pathPrefix, endpoint, requestParams);</span><br><span class="line">            HttpRequestBase request = createHttpRequest(method, uri, entity);</span><br><span class="line">            this.setHeaders(request, headers);</span><br><span class="line">            RestClient.FailureTrackingResponseListener failureTrackingResponseListener = new RestClient.FailureTrackingResponseListener(responseListener);</span><br><span class="line">            long startTime = System.nanoTime();</span><br><span class="line">            this.performRequestAsync(startTime, this.nextHost(), request, (Set)ignoreErrorCodes, httpAsyncResponseConsumerFactory, failureTrackingResponseListener);</span><br><span class="line">        &#125; catch (Exception var18) &#123;</span><br><span class="line">            responseListener.onFailure(var18);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    //已省略其他非必要代码。。。</span><br><span class="line"></span><br><span class="line">    private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) &#123;</span><br><span class="line">        String var3 = method.toUpperCase(Locale.ROOT);</span><br><span class="line">        byte var4 = -1;</span><br><span class="line">        switch(var3.hashCode()) &#123;</span><br><span class="line">        <span class="keyword">case</span> -531492226:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"OPTIONS"</span>)) &#123;</span><br><span class="line">                var4 = 3;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 70454:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"GET"</span>)) &#123;</span><br><span class="line">                var4 = 1;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 79599:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"PUT"</span>)) &#123;</span><br><span class="line">                var4 = 6;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 2213344:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"HEAD"</span>)) &#123;</span><br><span class="line">                var4 = 2;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 2461856:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"POST"</span>)) &#123;</span><br><span class="line">                var4 = 5;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 75900968:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"PATCH"</span>)) &#123;</span><br><span class="line">                var4 = 4;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 80083237:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"TRACE"</span>)) &#123;</span><br><span class="line">                var4 = 7;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">break</span>;</span><br><span class="line">        <span class="keyword">case</span> 2012838315:</span><br><span class="line">            <span class="keyword">if</span> (var3.equals(<span class="string">"DELETE"</span>)) &#123;</span><br><span class="line">                var4 = 0;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        switch(var4) &#123;</span><br><span class="line">        <span class="keyword">case</span> 0:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpDeleteWithEntity(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 1:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpGetWithEntity(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 2:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpHead(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 3:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpOptions(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 4:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpPatch(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 5:</span><br><span class="line">            HttpPost httpPost = new HttpPost(uri);</span><br><span class="line">            addRequestBody(httpPost, entity);</span><br><span class="line">            <span class="built_in">return</span> httpPost;</span><br><span class="line">        <span class="keyword">case</span> 6:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpPut(uri), entity);</span><br><span class="line">        <span class="keyword">case</span> 7:</span><br><span class="line">            <span class="built_in">return</span> addRequestBody(new HttpTrace(uri), entity);</span><br><span class="line">        default:</span><br><span class="line">            throw new UnsupportedOperationException(<span class="string">"http method not supported: "</span> + method);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>看到上面的代码，<strong>RestClient</strong> 类构造器的第一个参数是 <strong>CloseableHttpAsyncClient</strong>，是 Apache HTTP client 中的类，也就是说 <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.x/_motivations_around_a_new_java_client.html" target="_blank" rel="noopener">RestClient</a> 是基于 Apache HTTP 实现的，这里是 Apache HTTP 的依赖！</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;httpclient&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;<span class="variable">$&#123;http.version&#125;</span>&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<h2 id="Java-High-Level-REST-Client-1"><a href="#Java-High-Level-REST-Client-1" class="headerlink" title="Java High Level REST Client"></a>Java High Level REST Client</h2><p>最重要的是，我们发布了基于低级客户端的高级REST客户端，它负责请求编组和响应解组。</p>
<p>我们来看看 RestHighLevelClient 的底层代码！</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">package org.elasticsearch.client;</span><br><span class="line"></span><br><span class="line">public class RestHighLevelClient &#123;</span><br><span class="line">    private final RestClient client;</span><br><span class="line">    private final NamedXContentRegistry registry;</span><br><span class="line"></span><br><span class="line">    public RestHighLevelClient(RestClient restClient) &#123;</span><br><span class="line">        this(restClient, Collections.emptyList());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 此处省略多处代码！</span><br><span class="line"></span><br><span class="line">    // 该类大部分方法最终会调用以下 performRequestAndParseEntity 方法，我们主要看该方法的调用关系</span><br><span class="line"></span><br><span class="line">    protected &lt;Req extends ActionRequest, Resp&gt; Resp performRequestAndParseEntity(Req request, CheckedFunction&lt;Req, Request, IOException&gt; requestConverter, CheckedFunction&lt;XContentParser, Resp, IOException&gt; entityParser, Set&lt;Integer&gt; ignores, Header... headers) throws IOException &#123;</span><br><span class="line">        <span class="built_in">return</span> this.performRequest(request, requestConverter, (response) -&gt; &#123;</span><br><span class="line">            <span class="built_in">return</span> this.parseEntity(response.getEntity(), entityParser);</span><br><span class="line">        &#125;, ignores, headers);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    protected &lt;Req extends ActionRequest, Resp&gt; Resp performRequest(Req request, CheckedFunction&lt;Req, Request, IOException&gt; requestConverter, CheckedFunction&lt;Response, Resp, IOException&gt; responseConverter, Set&lt;Integer&gt; ignores, Header... headers) throws IOException &#123;</span><br><span class="line">        ActionRequestValidationException validationException = request.validate();</span><br><span class="line">        <span class="keyword">if</span> (validationException != null) &#123;</span><br><span class="line">            throw validationException;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            Request req = (Request)requestConverter.apply(request);</span><br><span class="line"></span><br><span class="line">            Response response;</span><br><span class="line">            try &#123;</span><br><span class="line">            </span><br><span class="line">                // 这里的 client 就是RestClient，最终还是调用 RestClient 的方法，也就是说 RestHighLevelClient 是基于 RestClient 的</span><br><span class="line">                </span><br><span class="line">                response = this.client.performRequest(req.getMethod(), req.getEndpoint(), req.getParameters(), req.getEntity(), headers);</span><br><span class="line">            &#125; catch (ResponseException var13) &#123;</span><br><span class="line">                ResponseException e = var13;</span><br><span class="line">                <span class="keyword">if</span> (ignores.contains(var13.getResponse().getStatusLine().getStatusCode())) &#123;</span><br><span class="line">                    try &#123;</span><br><span class="line">                        <span class="built_in">return</span> responseConverter.apply(e.getResponse());</span><br><span class="line">                    &#125; catch (Exception var11) &#123;</span><br><span class="line">                        throw this.parseResponseException(var13);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                throw this.parseResponseException(var13);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            try &#123;</span><br><span class="line">                <span class="built_in">return</span> responseConverter.apply(response);</span><br><span class="line">            &#125; catch (Exception var12) &#123;</span><br><span class="line">                throw new IOException(<span class="string">"Unable to parse response body for "</span> + response, var12);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>看上面的代码及注解，我相信你很快就豁然开朗了！</p>
<p>其实上面的问题现在就有答案了！TransportClient废弃的主要原因就是考虑到兼容性的问题，而后续两个客户端在兼容性方面就做的很好！</p>
<h1 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h1><p>关于Elasticsearch的客户端问题，其实 <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.x/_motivations_around_a_new_java_client.html" target="_blank" rel="noopener">ES官网</a> 已经说得很明确了，这里也通过代码剖析的方式去认识一下底层的代码，加深理解！</p>
<p>由此可见，HighLevelClient 是基于 RestClient,而 RestClient 又是基于 Apache HTTP 客户端， 这样一来, 在客户端方面, Elasticsearch 将 Java, Python, Php, Javascript 等各种语言的底层接口就都统一起来了; 与此同时, 使用 rest api, 还可以屏蔽各版本之前的差异。</p>
<p>这也提醒我们，在代码的升级过渡期, 处理好新 client 和旧 client 的关系，可以减少代码后期维护的工作量！</p>
<hr>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持是对我最大的鼓励</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById(&quot;QR&quot;); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="chloneda 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="chloneda 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        



  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>chloneda</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://chloneda.github.io/blog/es-clients/" title="Elasticsearch客户端源码剖析">https://chloneda.github.io/blog/es-clients/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Elasticsearch/" rel="tag"># Elasticsearch</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/hello-chloneda/" rel="next" title="Hello Chloneda">
                <i class="fa fa-chevron-left"></i> Hello Chloneda
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/es-shell/" rel="prev" title="Elasticsearch启动、停止脚本">
                Elasticsearch启动、停止脚本 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>
  
  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/chloneda.jpeg" alt="chloneda">
            
              <p class="site-author-name" itemprop="name">chloneda</p>
              <p class="site-description motion-element" itemprop="description">Less is more</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">31</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/rss2.html" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/chloneda" title="GitHub &rarr; https://github.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/chloneda" title="Twitter &rarr; https://twitter.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:chloneda@gmail.com" title="E-Mail &rarr; mailto:chloneda@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://weibo.com/chloneda" title="Weibo &rarr; https://weibo.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="http://www.zhihu.com/people/chl_vip" title="知乎 &rarr; http://www.zhihu.com/people/chl_vip" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>知乎</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.cnblogs.com/chloneda" title="博客园 &rarr; https://www.cnblogs.com/chloneda" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>博客园</a>
                </span>
              
            </div>
          

          

          
          


	  <div id="music163player">
		<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=5239700&auto=0&height=66"></iframe>
	  </div>

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ES客户端种类"><span class="nav-number">2.</span> <span class="nav-text">ES客户端种类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#客户端的使用"><span class="nav-number">3.</span> <span class="nav-text">客户端的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#TransportClient"><span class="nav-number">3.1.</span> <span class="nav-text">TransportClient</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-Low-Level-REST-Client"><span class="nav-number">3.2.</span> <span class="nav-text">Java Low Level REST Client</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-High-Level-REST-Client"><span class="nav-number">3.3.</span> <span class="nav-text">Java High Level REST Client</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#深入客户端的底层"><span class="nav-number">4.</span> <span class="nav-text">深入客户端的底层</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#TransportClient-1"><span class="nav-number">4.1.</span> <span class="nav-text">TransportClient</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-Low-Level-REST-Client-1"><span class="nav-number">4.2.</span> <span class="nav-text">Java Low Level REST Client</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-High-Level-REST-Client-1"><span class="nav-number">4.3.</span> <span class="nav-text">Java High Level REST Client</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#小结"><span class="nav-number">5.</span> <span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chloneda</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v7.0.0</div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.0"></script>

  <script src="/js/src/motion.js?v=7.0.0"></script>



  
  


  <script src="/js/src/schemes/muse.js?v=7.0.0"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.0"></script>
<script src="/js/src/post-details.js?v=7.0.0"></script>



  


  <script src="/js/src/bootstrap.js?v=7.0.0"></script>



  



  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
  
  <script>
    (function () {

      firebase.initializeApp({
        apiKey: '',
        projectId: ''
      })

      function getCount(doc, increaseCount) {
        //increaseCount will be false when not in article page

        return doc.get().then(function (d) {
          var count
          if (!d.exists) { //has no data, initialize count
            if (increaseCount) {
              doc.set({
                count: 1
              })
              count = 1
            }
            else {
              count = 0
            }
          }
          else { //has data
            count = d.data().count
            if (increaseCount) {
              if (!(window.localStorage && window.localStorage.getItem(title))) { //if first view this article
                doc.set({ //increase count
                  count: count + 1
                })
                count++
              }
            }
          }
          if (window.localStorage && increaseCount) { //mark as visited
            localStorage.setItem(title, true)
          }

          return count
        })
      }

      function appendCountTo(el) {
        return function (count) {
          $(el).append(
            $('<span>').addClass('post-visitors-count').append(
              $('<span>').addClass('post-meta-divider').text('|')
            ).append(
              $('<span>').addClass('post-meta-item-icon').append(
                $('<i>').addClass('fa fa-users')
              )
              ).append($('<span>').text('阅读次数 ' + count))
          )
        }
      }

      var db = firebase.firestore()
      var articles = db.collection('articles')

      //https://hexo.io/docs/variables.html
      var isPost = 'Elasticsearch客户端源码剖析'.length > 0
      var isArchive = '' === 'true'
      var isCategory = ''.length > 0
      var isTag = ''.length > 0

      if (isPost) { //is article page
        var title = 'Elasticsearch客户端源码剖析'
        var doc = articles.doc(title)

        getCount(doc, true).then(appendCountTo($('.post-meta')))
      }
      else if (!isArchive && !isCategory && !isTag) { //is index page
        var titles = [] //array to titles

        var postsstr = '' //if you have a better way to get titles of posts, please change it
        eval(postsstr)

        var promises = titles.map(function (title) {
          return articles.doc(title)
        }).map(function (doc) {
          return getCount(doc)
        })
        Promise.all(promises).then(function (counts) {
          var metas = $('.post-meta')
          counts.forEach(function (val, idx) {
            appendCountTo(metas[idx])(val)
          })
        })
      }
    })()
  </script>


  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function(i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap');
      $(e).after($wrap);
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
        var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
          return $(e).text();
        }).toArray().join('\n');
        var ta = document.createElement('textarea');
        var range = document.createRange(); //For Chrome
        var sel = window.getSelection(); //For Chrome
        var yPosition = window.pageYOffset || document.documentElement.scrollTop;
        ta.style.top = yPosition + 'px'; //Prevent page scroll
        ta.style.position = 'absolute';
        ta.style.opacity = '0';
        ta.value = code;
        ta.textContent = code; //For FireFox
        ta.contentEditable = true;
        ta.readOnly = false;
        document.body.appendChild(ta);
        range.selectNode(ta);
        sel.removeAllRanges();
        sel.addRange(range);
        ta.setSelectionRange(0, code.length);
        var result = document.execCommand('copy');
        
        ta.blur(); //For iOS
        $(this).blur();
      })).on('mouseleave', function(e) {
        var $b = $(this).find('.copy-btn');
        setTimeout(function() {
          $b.text('复制');
        }, 300);
      }).append(e);
    })
  </script>


</body>
</html>
